package RPC.rpc04;

import RPC.common.User;

import java.io.*;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Title
 * @Author zhengqiang.tan
 * @Date 11/14/22 10:27 PM
 */
public class Server {
    private static boolean running = true;

    public static void main(String[] args) throws Exception {
        ServerSocket socket = new ServerSocket(8888);
        while (running) {
            Socket accept = socket.accept();
            process(accept);
            accept.close();
        }
        socket.close();
        System.out.println("启动服务器...");


    }

    /**
     * 对同一个接口下任意方法的支持
     *
     * @param s
     * @throws Exception
     */
    private static void process(Socket s) throws Exception {
        InputStream in = s.getInputStream();
        OutputStream out = s.getOutputStream();
        ObjectInputStream ois = new ObjectInputStream(in);
        DataOutputStream dos = new DataOutputStream(out);

        //服务器端解析这三个参数 并找到对应的方法
        String methodName = ois.readUTF();
        Class[] paramTypes = (Class[]) ois.readObject();
        Object[] args = (Object[]) ois.readObject();


        UserServiceImpl userService = new UserServiceImpl();
        Method method = userService.getClass().getMethod(methodName, paramTypes);
        User user = (User) method.invoke(userService, args);

        dos.writeInt(user.getId());
        dos.writeUTF(user.getName());

        dos.flush();

    }
}
